
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <cerrno>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

using namespace std;

struct ThreadData
{
    int sockfd;
    struct sockaddr_in server;
};

void Usage(char *argv)
{
    std::cout << "Usage: " << argv << " ip:   port: " << std::endl;
}

void *SendMessage(void *args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    string message;
    while (1)
    {
        cout << "Please Enter# ";
        getline(cin, message);

        // 发送消息
        //std::cout << message << std::endl;
        socklen_t len = sizeof(td->server);
        sendto(td->sockfd, message.c_str(), message.size(), 0, (const struct sockaddr *)&(td->server), len);
    }
}

void *RecvMessage(void *args)
{
    ThreadData* td = static_cast<ThreadData*>(args);
    char buff[1024];
    while (1)
    {
        // 接收消息
        struct sockaddr_in temp;
        socklen_t templen = sizeof(temp);

        int n = recvfrom(td->sockfd, buff, sizeof(buff) - 1, 0, (struct sockaddr *)&temp, &templen);
        if (n > 0)
        {
            buff[n] = 0;
            std::cerr << buff << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);

    //创建ThreadData传入线程
    ThreadData td;

    // 创建套接字
    td.sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (td.sockfd < 0)
    {
        std::cerr << "socket create failed ,errno: " << errno << " ,err string " << strerror(errno) << std::endl;
    }
    std::cout << "socket create success" << std::endl;

    
    memset(&td.server, 0, sizeof(td.server));
    td.server.sin_family = AF_INET;
    td.server.sin_port = htons(port);                  // 主机转网络
    td.server.sin_addr.s_addr = inet_addr(ip.c_str()); // 1.字符串转成整型  2.主机转网络
    

    // 多线程版本接受信息和发送信息
    pthread_t recvr, sender;
    pthread_create(&recvr, nullptr, RecvMessage, &td);
    pthread_create(&sender, nullptr, SendMessage, &td);

    pthread_join(recvr, nullptr);
    pthread_join(sender, nullptr);


    return 0;
}